import React, { useEffect, useState, useRef, useMemo } from 'react';
import { CopyOutlined, DeleteOutlined, LinkOutlined } from '@ant-design/icons';
import type { CanvasElement } from './types';
import RealTimeMonitoring from '@/pages/Device/Manager/modules/tabs/RealTimeMonitoring';
import type { Color } from 'antd/es/color-picker';
import CustomUpload from '@/components/CustomUpload';
import RemoteSelect from '@/components/RemoteSelect';
import { useImageColor } from '@/hooks/useImageColor';
import {
  deviceManagerListApi,
  deviceManagerDetailApi,
  deviceManagerReportApi,
  type DeviceItemDetail,
} from '@/api/deviceManagerApi';
import { deviceGroupListApi } from '@/api/deviceGroupApi';
import './DeviceDrawer.css';

const colorPresets = [
  {
    label: '预设颜色',
    colors: [
      'transparent',
      '#FFFFFF',
      '#000000',
      '#F5222D',
      '#FA8C16',
      '#FADB14',
      '#52C41A',
      '#13C2C2',
      '#1677FF',
      '#722ED1',
      '#EB2F96',
      '#BFBFBF',
      '#8C8C8C',
      '#595959',
      '#262626',
      '#FAFAFA',
    ],
  },
];

const { Option } = ASelect;

// 定义FetchParams类型
interface FetchParams {
  page: number;
  pageSize: number;
  searchValue?: string;
  [key: string]: any;
}

/** 获取设备列表 */
const fetchRemoteSelectDataDevice = async (params: FetchParams) => {
  const res = await deviceManagerListApi(params);
  if (res.success) {
    const { page, pageSize } = params;
    const hasMore = page * pageSize < res.data.total;

    return {
      data: res.data.records.map(v => {
        return {
          ...v,
          label: `${v.deviceName}-${v.code}`,
          value: v.id,
        };
      }),
      total: res.data.total,
      hasMore,
    };
  }
  return {
    data: [],
    total: 0,
    hasMore: false,
  };
};

/** 获取设备分组列表 */
const fetchRemoteSelectDataDeviceGroup = async (params: FetchParams) => {
  const res = await deviceGroupListApi(params);
  if (res.success) {
    const { page, pageSize } = params;
    const hasMore = page * pageSize < res.data.total;

    return {
      data: res.data.records.map(v => {
        return {
          ...v,
          label: `${v.groupName}(${v.deviceCount || 0})`,
          value: v.id,
        };
      }),
      total: res.data.total,
      hasMore,
    };
  }
  return {
    data: [],
    total: 0,
    hasMore: false,
  };
};

/**
 * 属性面板组件属性
 */
interface PropertyPanelProps {
  selectedElement: CanvasElement | any | null; // Allow edge type
  onUpdateElement: (id: string, newPartialElement: Partial<CanvasElement> | any) => void;
  onRemoveElement: (id: string) => void;
  onDuplicateElement: (id: string) => void;
  canvasConfig?: { grid: any; background: any };
  onCanvasConfigChange?: (config: { grid?: any; background?: any }) => void;
}

/**
 * 属性面板组件
 * 用于编辑选中元素的属性，支持节点和连线
 */
const PropertyPanel: React.FC<PropertyPanelProps> = ({
  selectedElement,
  onUpdateElement,
  onRemoveElement,
  onDuplicateElement,
  canvasConfig,
  onCanvasConfigChange,
}) => {
  const [form] = AForm.useForm();
  const [canvasForm] = AForm.useForm();
  const [activeKeys, setActiveKeys] = useState<string[]>(['title']);
  const [deviceInfo, setDeviceInfo] = useState<any>({});

  const selectedElementRef = useRef(selectedElement);
  selectedElementRef.current = selectedElement;
  console.log('1111', selectedElement);
  const isEdge = selectedElement && selectedElement.source && selectedElement.target;
  const isNode = selectedElement && !isEdge;
  // 判断是否为设备组件（可以根据实际的设备类型判断逻辑调整）
  const isDeviceComponent = isNode;

  // 判断是否为背景元素或被锁定的元素
  const isBackgroundOrLocked =
    selectedElement &&
    (selectedElement.type === 'background' || selectedElement.properties?.locked);

  // 设备绑定相关状态
  const [_deviceBindType, setDeviceBindType] = useState<number>(1);
  const [bindDrawerVisible, setBindDrawerVisible] = useState(false);
  const [bindLoading, setBindLoading] = useState(false);
  const [deviceDetail, setDeviceDetail] = useState<DeviceItemDetail | null>(null);
  const [monitoringData, setMonitoringData] = useState<any>(null);
  const [reportData, setReportData] = useState<any>([]);

  // 监听表单中的绑定类型和分组变化
  const bindType = AForm.useWatch('bindType', form);
  const groupId = AForm.useWatch('groupId', form);

  // 当绑定类型或分组变化时清空设备选择
  useEffect(() => {
    form.setFieldsValue({
      deviceId: undefined,
      deviceInfo: undefined,
    });
  }, [bindType, groupId]);

  const backgroundImageEnabled = AForm.useWatch('backgroundImageEnabled', canvasForm);
  const gridType = AForm.useWatch('gridType', canvasForm);

  // 从背景图片中提取主色调并更新背景颜色
  const backgroundImageUrlFileList = AForm.useWatch('backgroundImageUrlFileList', canvasForm);
  const imageUrl = backgroundImageUrlFileList?.[0]?.url;
  const dominantColor = useImageColor(imageUrl || '');

  useEffect(() => {
    if (dominantColor) {
      canvasForm.setFieldsValue({ backgroundColor: dominantColor });
    }
  }, [dominantColor, canvasForm]);

  const deviceParams = useMemo(() => {
    return {
      groupId: bindType == 1 ? '' : groupId,
    };
  }, [groupId, bindType]);

  const toHexString = (color: Color | string) => {
    if (typeof color === 'string') return color;
    if (color && typeof color.toHexString === 'function') return color.toHexString();
    return '#000000';
  };

  // 获取设备详情
  const fetchDeviceDetail = async (id: string) => {
    try {
      const res = await deviceManagerDetailApi({ id: Number(id) });
      if (res.success) {
        const deviceData = res.data as DeviceItemDetail;
        deviceData.metaDataJson = JSON.parse(deviceData.metaData || '{}');
        setDeviceDetail(deviceData);
        // 获取设备详情成功后，获取设备上报数据
        if (deviceData.productCode && deviceData.code) {
          fetchDeviceReportData(deviceData.productCode, deviceData.code);
        }
      }
    } catch (error) {
      console.error('获取设备详情失败:', error);
    }
  };
  const fetchDeviceReportData = async (productCode: string, deviceCode: string) => {
    try {
      const res = await deviceManagerReportApi({ productCode, deviceCode });
      if (res.success) {
        setReportData(res.data);
      }
    } catch (error) {
      console.error('获取设备上报数据失败:', error);
      // 不显示错误消息，因为这不是关键功能
    }
  };

  // 处理设备绑定
  const handleDeviceBind = async () => {
    try {
      setBindLoading(true);
      const values = await form.validateFields(['bindType', 'groupId', 'deviceId']);
      if (!values.deviceId) {
        window.$message.warning('请选择要绑定的设备');
        return;
      }

      // 模拟绑定过程
      // await new Promise(resolve => setTimeout(resolve, 1000));
      // console.log('222222', selectedElement, values);

      // 直接更新元素属性，不使用嵌套的properties结构
      // 这样可以避免properties内部再嵌套properties的问题
      onUpdateElement(selectedElement!.id, {
        bindType: values.bindType,
        deviceId: values.deviceId,
        deviceInfo: deviceInfo,
        groupId: values.groupId,
      });

      // 获取设备详情
      await fetchDeviceDetail(values.deviceId);

      window.$message.success('设备绑定成功！');
      setBindDrawerVisible(false);
    } catch (error) {
      window.$message.error('设备绑定失败，请重试');
    } finally {
      setBindLoading(false);
    }
  };

  // 监听设备ID变化，自动获取设备详情
  useEffect(() => {
    const deviceId = form.getFieldValue('deviceId');
    if (deviceId) {
      fetchDeviceDetail(deviceId);
    } else {
      setDeviceDetail(null);
      setMonitoringData(null);
    }
  }, [form.getFieldValue('deviceId')]);

  // 当选中元素变化时，更新表单内容
  useEffect(() => {
    if (selectedElement) {
      if (isNode) {
        // 合并顶层属性和properties中的属性，优先使用顶层属性
        const initialValues = {
          ...selectedElement,
          ...selectedElement.properties,
          textContent: selectedElement.properties.textContent ?? '',
          zIndex: selectedElement.zIndex,
          labelEnabled: selectedElement.properties.labelEnabled ?? true,
          labelFontWeight: selectedElement.properties.labelFontWeight ?? 'normal',
          labelPosition: selectedElement.properties.labelPosition ?? 'bottom',
          labelVSpan: selectedElement.properties.labelVSpan ?? 10,
          labelHSpan: selectedElement.properties.labelHSpan ?? 0,
          backgroundEnabled: selectedElement.properties.backgroundEnabled ?? false,
          borderEnabled: selectedElement.properties.borderEnabled ?? false,
          borderWidth: selectedElement.properties.borderWidth ?? 1,
          borderColor: selectedElement.properties.borderColor ?? '#5F95FF',
          borderStyle: selectedElement.properties.borderStyle ?? 'solid',
          backgroundFit: selectedElement.properties.backgroundFit ?? 'cover',
          backgroundPosition: selectedElement.properties.backgroundPosition ?? 'center',
          // 设备绑定相关的初始值，优先使用顶层属性，其次使用properties中的属性
          bindType: selectedElement.bindType ?? selectedElement.properties.bindType ?? 1,
          groupId: selectedElement.groupId ?? selectedElement.properties.groupId ?? undefined,
          deviceId: selectedElement.deviceId ?? selectedElement.properties.deviceId ?? undefined,
          deviceInfo:
            selectedElement.deviceInfo ?? selectedElement.properties.deviceInfo ?? undefined,
        };
        if (initialValues.deviceInfo) {
          setDeviceInfo(initialValues.deviceInfo);
        }

        if (selectedElement.properties?.imageUrl) {
          initialValues.imageUrlFileList = [
            {
              uid: '-1',
              name: 'image.png',
              status: 'done',
              url: selectedElement.properties.imageUrl,
            },
          ];
        } else {
          initialValues.imageUrlFileList = [];
        }

        form.setFieldsValue(initialValues);

        // 如果有设备ID，自动获取设备详情
        if (initialValues.deviceId) {
          fetchDeviceDetail(initialValues.deviceId);
        }

        const newActiveKeys = ['title'];
        if (initialValues.backgroundEnabled) newActiveKeys.push('background');
        if (initialValues.borderEnabled) newActiveKeys.push('border');
        setActiveKeys(newActiveKeys);
      } else if (isEdge) {
        // 确保连线的默认值设置完整
        const defaultStroke = selectedElement.attrs?.line?.stroke || '#5F95FF';
        const defaultStrokeWidth = selectedElement.attrs?.line?.strokeWidth || 2;
        const defaultStrokeDasharray = selectedElement.attrs?.line?.strokeDasharray || 'solid';

        const edgeValues = {
          attrs: {
            line: {
              stroke: defaultStroke,
              strokeWidth: defaultStrokeWidth,
              strokeDasharray: defaultStrokeDasharray === 'none' ? 'solid' : defaultStrokeDasharray,
              targetMarker: {
                name: selectedElement.attrs?.line?.targetMarker?.name || 'classic',
                size: selectedElement.attrs?.line?.targetMarker?.size || 8,
                fill: selectedElement.attrs?.line?.targetMarker?.fill || defaultStroke,
              },
              sourceMarker: {
                name: selectedElement.attrs?.line?.sourceMarker?.name || '',
                size: selectedElement.attrs?.line?.sourceMarker?.size || 8,
                fill: selectedElement.attrs?.line?.sourceMarker?.fill || defaultStroke,
              },
            },
          },
          router: {
            name: selectedElement.router?.name || 'er',
            args: selectedElement.router?.args || { direction: 'H' },
          },
          connector: {
            name: selectedElement.connector?.name || 'rounded',
            args: selectedElement.connector?.args || {},
          },
          zIndex: selectedElement.zIndex || 1000,
        };

        form.setFieldsValue(edgeValues);
      }
    } else {
      form.resetFields();
      setActiveKeys(['title']);
      // 当没有选中元素时，初始化画布设置表单
      if (canvasConfig) {
        canvasForm.setFieldsValue({
          gridVisible: canvasConfig.grid.visible,
          gridType: canvasConfig.grid.type,
          gridSize: canvasConfig.grid.size,
          gridColor: canvasConfig.grid.args[0]?.color,
          gridThickness: canvasConfig.grid.args[0]?.thickness,
          gridColorSecond: canvasConfig.grid.args[1]?.color,
          gridThicknessSecond: canvasConfig.grid.args[1]?.thickness,
          gridFactor: canvasConfig.grid.args[1]?.factor,

          backgroundVisible: canvasConfig.background.visible,
          backgroundColor: canvasConfig.background.color,
          backgroundImageEnabled: canvasConfig.background.backgroundImageEnabled,
          backgroundImageFit: canvasConfig.background.size,
          backgroundImagePosition: canvasConfig.background.position,
          backgroundImageRepeat: canvasConfig.background.repeat,
          backgroundOpacity: canvasConfig.background.opacity,
          backgroundImageUrlFileList: canvasConfig.background.image
            ? [
                {
                  uid: '-1',
                  name: 'background.png',
                  status: 'done',
                  url: canvasConfig.background.image,
                },
              ]
            : [],
        });
      }
    }
  }, [selectedElement, form, isNode, isEdge, canvasForm, canvasConfig]);

  // 处理画布设置表单值变化
  const handleCanvasValuesChange = (_: any, allValues: any) => {
    if (!onCanvasConfigChange) return;

    const {
      gridVisible,
      gridType,
      gridSize,
      gridColor,
      gridThickness,
      gridColorSecond,
      gridThicknessSecond,
      gridFactor,
      backgroundVisible,
      backgroundColor,
      backgroundImageEnabled,
      backgroundImageUrlFileList,
      backgroundImageFit,
      backgroundImagePosition,
      backgroundImageRepeat,
      backgroundOpacity,
    } = allValues;

    const grid = {
      visible: gridVisible,
      type: gridType || 'mesh',
      size: gridSize || 10,
      args: [
        {
          color: toHexString(gridColor) || '#e5e5e5',
          thickness: gridThickness || 1,
        },
      ],
    };

    if (grid.type === 'doubleMesh') {
      grid.args.push({
        color: toHexString(gridColorSecond) || '#888888',
        thickness: gridThicknessSecond || 3,
        factor: gridFactor || 4,
      });
    }

    const background = {
      visible: backgroundVisible,
      color: toHexString(backgroundColor),
      image: backgroundImageEnabled ? backgroundImageUrlFileList?.[0]?.url : undefined,
      repeat: backgroundImageRepeat || 'no-repeat',
      size: backgroundImageFit || 'cover',
      position: backgroundImagePosition || 'center',
      opacity: backgroundOpacity,
      backgroundImageEnabled,
    };

    onCanvasConfigChange({ grid, background });
  };

  // 处理表单值变化
  const handleValuesChange = (_: any, allValues: any) => {
    const currentSelected = selectedElementRef.current;
    if (!currentSelected) return;

    const newValues = { ...allValues };

    if (isNode) {
      if (newValues.imageUrlFileList && newValues.imageUrlFileList.length > 0) {
        newValues.imageUrl = newValues.imageUrlFileList[0].url;
      } else {
        newValues.imageUrl = '';
      }
    }

    if (isEdge) {
      // 处理连线属性更新
      if (newValues.attrs?.line?.stroke) {
        newValues.attrs.line.stroke = toHexString(newValues.attrs.line.stroke);
      }
      if (newValues.attrs?.line?.targetMarker?.fill) {
        const markerColor = toHexString(newValues.attrs.line.targetMarker.fill);
        newValues.attrs.line.targetMarker.fill = markerColor;
        newValues.attrs.line.targetMarker.stroke = markerColor; // Set stroke for complete coloring
      }
      if (newValues.attrs?.line?.sourceMarker?.fill) {
        const markerColor = toHexString(newValues.attrs.line.sourceMarker.fill);
        newValues.attrs.line.sourceMarker.fill = markerColor;
        newValues.attrs.line.sourceMarker.stroke = markerColor; // Set stroke for complete coloring
      }

      // 处理线条样式
      if (newValues.attrs?.line?.strokeDasharray) {
        if (newValues.attrs.line.strokeDasharray === 'solid') {
          newValues.attrs.line.strokeDasharray = 'none';
        }
      }

      // 处理箭头标记的特殊情况
      if (newValues.attrs?.line?.targetMarker) {
        // 如果设置为空字符串，删除targetMarker属性
        if (
          newValues.attrs.line.targetMarker.name === '' ||
          newValues.attrs.line.targetMarker.name === null
        ) {
          delete newValues.attrs.line.targetMarker;
        } else if (!newValues.attrs.line.targetMarker.fill) {
          newValues.attrs.line.targetMarker.fill = newValues.attrs.line.stroke || '#5F95FF';
        }
      }
      if (newValues.attrs?.line?.sourceMarker) {
        // 如果设置为空字符串，删除sourceMarker属性
        if (
          newValues.attrs.line.sourceMarker.name === '' ||
          newValues.attrs.line.sourceMarker.name === null
        ) {
          delete newValues.attrs.line.sourceMarker;
        } else if (!newValues.attrs.line.sourceMarker.fill) {
          newValues.attrs.line.sourceMarker.fill = newValues.attrs.line.stroke || '#5F95FF';
        }
      }

      // 处理router和connector
      if (newValues.router) {
        // 确保router对象存在且有name属性
        if (!newValues.router.name) {
          newValues.router.name = 'er'; // 默认值
        }
      }

      if (newValues.connector) {
        // 确保connector对象存在且有name属性
        if (!newValues.connector.name) {
          newValues.connector.name = 'rounded'; // 默认值
        }
      }
    } else {
      // 处理节点属性更新
      if (newValues.labelColor) newValues.labelColor = toHexString(newValues.labelColor);
      if (newValues.backgroundColor)
        newValues.backgroundColor = toHexString(newValues.backgroundColor);
      if (newValues.borderColor) newValues.borderColor = toHexString(newValues.borderColor);

      // 处理设备绑定相关的数据更新
      if (newValues.bindType !== undefined) {
        setDeviceBindType(newValues.bindType);
      }
    }

    onUpdateElement(currentSelected.id, newValues);
  };

  const handleActiveKeyChange = (keys: string | string[]) => {
    setActiveKeys(typeof keys === 'string' ? [keys] : keys);
  };

  const getZIndexRange = () => {
    if (isEdge) {
      return { min: 1000, max: 9999 };
    }
    if (isNode) {
      if (selectedElement?.type === 'background') {
        return { min: 1, max: 99 };
      } else {
        return { min: 100, max: 999 };
      }
    }
    return { min: 0, max: 9999 }; // Fallback
  };

  const zIndexRange = getZIndexRange();

  // 渲染节点属性
  const renderNodeProperties = () => {
    const appearanceItems = [
      {
        key: 'title',
        label: <span style={{ fontWeight: 'bold' }}>标题</span>,
        extra: (
          <AForm.Item name="labelEnabled" valuePropName="checked" noStyle>
            <ASwitch size="small" />
          </AForm.Item>
        ),
        children: (
          <>
            {selectedElement?.type === 'text' && (
              <AForm.Item label="内容" name="textContent">
                <AInput.TextArea rows={3} placeholder="请输入文本内容" />
              </AForm.Item>
            )}
            <AForm.Item label="颜色" name="labelColor">
              <AColorPicker showText presets={colorPresets} />
            </AForm.Item>
            <AForm.Item label="字体大小" name="labelFontSize">
              <AInputNumber style={{ width: '100%' }} min={8} defaultValue={12} />
            </AForm.Item>
            <AForm.Item label="字体加粗" name="labelFontWeight">
              <ASelect style={{ width: '100%' }}>
                <Option value="bold">是</Option>
                <Option value="normal">否</Option>
              </ASelect>
            </AForm.Item>
            {selectedElement?.type === 'text' && (
              <AForm.Item label="是否换行" name="labelWrap">
                <ASelect style={{ width: '100%' }}>
                  <Option value="normal">是</Option>
                  <Option value="nowrap">否</Option>
                </ASelect>
              </AForm.Item>
            )}
            <AForm.Item label="垂直间距" name="labelVSpan">
              <AInputNumber style={{ width: '100%' }} />
            </AForm.Item>
            <AForm.Item label="水平间距" name="labelHSpan">
              <AInputNumber style={{ width: '100%' }} />
            </AForm.Item>
            <AForm.Item label="位置" name="labelPosition">
              <ASelect>
                <Option value="bottom">下</Option>
                <Option value="top">上</Option>
                <Option value="left-center">左中</Option>
                <Option value="right-center">右中</Option>
                <Option value="center">中</Option>
                <Option value="top-left">左上</Option>
                <Option value="top-right">右上</Option>
                <Option value="bottom-left">左下</Option>
                <Option value="bottom-right">右下</Option>
              </ASelect>
            </AForm.Item>
          </>
        ),
      },
      {
        key: 'background',
        label: '背景',
        extra: (
          <AForm.Item name="backgroundEnabled" valuePropName="checked" noStyle>
            <ASwitch size="small" />
          </AForm.Item>
        ),
        children: (
          <>
            <AForm.Item label="背景颜色" name="backgroundColor">
              <AColorPicker showText presets={colorPresets} />
            </AForm.Item>
            {(selectedElement?.type === 'background' || selectedElement?.type === 'image') && (
              <>
                <AForm.Item label="背景图片" name="imageUrlFileList">
                  <CustomUpload
                    maxCount={1}
                    multiple={false}
                    accept="image/png, image/jpeg, image/gif, image/svg+xml"
                    listType="picture-card"
                  />
                </AForm.Item>
                <AForm.Item label="图片适应" name="backgroundFit">
                  <ASelect>
                    <Option value="cover">覆盖 (Cover)</Option>
                    <Option value="contain">适应 (Contain)</Option>
                    <Option value="fill">拉伸 (Fill)</Option>
                  </ASelect>
                </AForm.Item>
                <AForm.Item label="图片重复" name="backgroundImageRepeat">
                  <ASelect>
                    <Option value="repeat">平铺 (Repeat)</Option>
                    <Option value="no-repeat">不重复 (No Repeat)</Option>
                    <Option value="repeat-x">水平重复 (Repeat-X)</Option>
                    <Option value="repeat-y">垂直重复 (Repeat-Y)</Option>
                  </ASelect>
                </AForm.Item>
                <AForm.Item label="图片位置" name="backgroundPosition">
                  <ASelect>
                    <Option value="center">居中 (Center)</Option>
                    <Option value="left top">左上 (Left Top)</Option>
                    <Option value="left center">左中 (Left Center)</Option>
                    <Option value="left bottom">左下 (Left Bottom)</Option>
                    <Option value="right top">右上 (Right Top)</Option>
                    <Option value="right center">右中 (Right Center)</Option>
                    <Option value="right bottom">右下 (Right Bottom)</Option>
                    <Option value="center top">中上 (Center Top)</Option>
                    <Option value="center bottom">中下 (Center Bottom)</Option>
                  </ASelect>
                </AForm.Item>
              </>
            )}
          </>
        ),
      },
      {
        key: 'border',
        label: '边框',
        extra: (
          <AForm.Item name="borderEnabled" valuePropName="checked" noStyle>
            <ASwitch size="small" />
          </AForm.Item>
        ),
        children: (
          <>
            <AForm.Item label="边框宽度" name="borderWidth">
              <AInputNumber style={{ width: '100%' }} min={0} />
            </AForm.Item>
            <AForm.Item label="边框颜色" name="borderColor">
              <AColorPicker showText presets={colorPresets} />
            </AForm.Item>
            <AForm.Item label="边框样式" name="borderStyle">
              <ASelect>
                <Option value="solid">实线</Option>
                <Option value="dashed">虚线</Option>
                <Option value="dotted">点线</Option>
              </ASelect>
            </AForm.Item>
          </>
        ),
      },
    ];

    const nodeTabs = [
      {
        key: '1',
        label: '元素',
        children: (
          <div className="p-4 pt-0">
            <AForm.Item label="名称" name="name">
              <AInput />
            </AForm.Item>
            <AForm.Item label="层级" name="zIndex">
              <AInputNumber style={{ width: '100%' }} min={zIndexRange.min} max={zIndexRange.max} />
            </AForm.Item>
            <AForm.Item label="X坐标" name={['position', 'x']}>
              <AInputNumber style={{ width: '100%' }} disabled={isBackgroundOrLocked} />
            </AForm.Item>
            <AForm.Item label="Y坐标" name={['position', 'y']}>
              <AInputNumber style={{ width: '100%' }} disabled={isBackgroundOrLocked} />
            </AForm.Item>
            <AForm.Item label="宽度" name={['size', 'width']}>
              <AInputNumber style={{ width: '100%' }} min={1} disabled={isBackgroundOrLocked} />
            </AForm.Item>
            <AForm.Item label="高度" name={['size', 'height']}>
              <AInputNumber style={{ width: '100%' }} min={1} disabled={isBackgroundOrLocked} />
            </AForm.Item>
            <AForm.Item label="角度" name="angle">
              <AInputNumber
                style={{ width: '100%' }}
                min={0}
                max={360}
                disabled={isBackgroundOrLocked}
              />
            </AForm.Item>
          </div>
        ),
      },
      {
        key: '2',
        label: '外观',
        children: (
          <div className="p-4 pt-0">
            <ACollapse
              items={appearanceItems}
              activeKey={activeKeys}
              onChange={handleActiveKeyChange}
              ghost
            />
          </div>
        ),
      },
      // 只有设备组件才显示设备tab
      ...(isDeviceComponent
        ? [
            {
              key: '3',
              label: '设备',
              children: (
                <div className="h-full flex flex-col">
                  {/* 顶部绑定按钮 */}
                  <div className="p-4 border-b border-gray-100">
                    <AButton
                      type="primary"
                      icon={<LinkOutlined />}
                      size="large"
                      block
                      onClick={() => setBindDrawerVisible(true)}
                      className="h-12 text-base font-medium shadow-sm hover:shadow-md transition-all duration-200"
                    >
                      {form.getFieldValue('deviceId') ? '重新绑定设备' : '绑定设备'}
                    </AButton>
                  </div>

                  {/* 设备信息卡片 */}
                  {deviceDetail && (
                    <div className="p-4 border-b border-gray-100">
                      <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 border border-blue-100">
                        <div className="flex items-center justify-between mb-3">
                          <h3 className="text-lg font-semibold text-gray-800">设备信息</h3>
                          <ATag color={deviceDetail.status === 1 ? 'success' : 'error'}>
                            {deviceDetail.status === 1 ? '在线' : '离线'}
                          </ATag>
                        </div>

                        <div className="grid grid-cols-1 gap-3">
                          <div className="flex justify-between items-center">
                            <span className="text-gray-600 text-sm">设备名称:</span>
                            <span className="font-medium text-gray-800">
                              {deviceDetail.deviceName}
                            </span>
                          </div>
                          <div className="flex justify-between items-center">
                            <span className="text-gray-600 text-sm">设备编码:</span>
                            <span className="font-mono text-sm text-gray-700">
                              {deviceDetail.code}
                            </span>
                          </div>
                          <div className="flex justify-between items-center">
                            <span className="text-gray-600 text-sm">产品型号:</span>
                            <span className="text-gray-700">{deviceDetail.productName}</span>
                          </div>
                          <div className="flex justify-between items-center">
                            <span className="text-gray-600 text-sm">最近在线:</span>
                            <span className="text-gray-700 text-xs">
                              {deviceDetail.latestOnlineTime || '未知'}
                            </span>
                          </div>
                          {deviceDetail.address && (
                            <div className="flex justify-between items-center">
                              <span className="text-gray-600 text-sm">位置信息:</span>
                              <span
                                className="text-gray-700 text-xs max-w-32 truncate"
                                title={deviceDetail.address}
                              >
                                {deviceDetail.address}
                              </span>
                            </div>
                          )}
                        </div>

                        <div className="mt-3 pt-3 border-t border-blue-200">
                          <AButton
                            type="link"
                            size="small"
                            danger
                            onClick={() => {
                              form.setFieldValue('deviceId', undefined);
                              setDeviceDetail(null);
                              setMonitoringData(null);
                            }}
                            className="p-0 h-auto text-red-500 hover:text-red-600"
                          >
                            解绑设备
                          </AButton>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 实时监控模块 */}
                  {deviceDetail && (
                    <div className="flex-1 p-4">
                      <RealTimeMonitoring
                        deviceDetail={deviceDetail}
                        reportData={reportData}
                        type="col"
                        reportLoading={false}
                        onSwitchToPropertyRecords={() => {}}
                        onSwitchToServiceRecords={() => {}}
                      />
                    </div>
                  )}

                  {/* 未绑定设备时的提示 */}
                  {!deviceDetail && (
                    <div className="flex-1 flex items-center justify-center p-8">
                      <div className="text-center text-gray-400">
                        <LinkOutlined className="text-4xl mb-4" />
                        <p className="text-base">请先绑定设备</p>
                        <p className="text-sm mt-2">绑定后可查看设备信息和实时监控数据</p>
                      </div>
                    </div>
                  )}

                  {/* 设备绑定抽屉 */}
                  <ADrawer
                    title="设备绑定"
                    placement="right"
                    onClose={() => setBindDrawerVisible(false)}
                    open={bindDrawerVisible}
                    width={400}
                    className="device-bind-drawer"
                    styles={{
                      body: { padding: 0 },
                    }}
                    extra={
                      <ASpace>
                        <AButton onClick={() => setBindDrawerVisible(false)}>取消</AButton>
                        <AButton type="primary" loading={bindLoading} onClick={handleDeviceBind}>
                          确认绑定
                        </AButton>
                      </ASpace>
                    }
                  >
                    <div className="p-6">
                      <div className="mb-6">
                        <h3 className="text-lg font-semibold text-gray-800 mb-2">绑定设备到组件</h3>
                        <p className="text-gray-600 text-sm">
                          选择要绑定的设备，绑定后可在组件中查看设备的实时状态和监控数据。
                        </p>
                      </div>

                      <div className="space-y-6">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-2">
                            绑定类型
                          </label>
                          <AForm.Item name="bindType" initialValue={1} className="mb-0">
                            <ARadio.Group
                              onChange={e => {
                                setDeviceBindType(e.target.value);
                                form.setFieldsValue({
                                  deviceId: undefined,
                                  deviceInfo: undefined,
                                });
                              }}
                              className="w-full"
                            >
                              <ARadio.Button value={1} className="flex-1 text-center">
                                直接选择
                              </ARadio.Button>
                              <ARadio.Button value={2} className="flex-1 text-center">
                                按分组选择
                              </ARadio.Button>
                            </ARadio.Group>
                          </AForm.Item>
                        </div>

                        {bindType === 2 && (
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                              选择设备分组
                            </label>
                            <AForm.Item name="groupId" className="mb-0">
                              <RemoteSelect
                                onSelect={() => {
                                  form.setFieldValue('deviceId', undefined);
                                }}
                                searchable
                                placeholder="请选择设备分组"
                                fetchData={fetchRemoteSelectDataDeviceGroup}
                                className="w-full"
                              />
                            </AForm.Item>
                          </div>
                        )}

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-2">
                            选择设备 <span className="text-red-500">*</span>
                          </label>
                          <AForm.Item
                            name="deviceId"
                            className="mb-0"
                            rules={[{ required: true, message: '请选择要绑定的设备' }]}
                          >
                            <RemoteSelect
                              searchable
                              searchParams={deviceParams}
                              placeholder="搜索并选择设备"
                              fetchData={fetchRemoteSelectDataDevice}
                              onChange={(e, eve) => {
                                setDeviceInfo(eve.data);
                              }}
                              className="w-full"
                            />
                          </AForm.Item>
                        </div>

                        {form.getFieldValue('deviceId') && (
                          <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                            <div className="flex items-center">
                              <div className="w-2 h-2 bg-green-500 rounded-full mr-2"></div>
                              <span className="text-green-700 font-medium">已选择设备</span>
                            </div>
                            <div className="mt-2 text-sm text-green-600">
                              设备Id: {form.getFieldValue('deviceId')}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </ADrawer>
                </div>
              ),
            },
          ]
        : []),
    ];

    return <ATabs defaultActiveKey="1" size="small" centered items={nodeTabs} />;
  };

  // 渲染连线属性
  const renderEdgeProperties = () => {
    const edgeTabs = [
      {
        key: '1',
        label: '样式',
        children: (
          <div className="p-4 pt-0">
            <ACollapse
              defaultActiveKey={['line']}
              ghost
              items={[
                {
                  key: 'line',
                  label: '线条样式',
                  children: (
                    <>
                      <AForm.Item label="颜色" name={['attrs', 'line', 'stroke']}>
                        <AColorPicker showText presets={colorPresets} />
                      </AForm.Item>
                      <AForm.Item label="线宽" name={['attrs', 'line', 'strokeWidth']}>
                        <AInputNumber style={{ width: '100%' }} min={1} />
                      </AForm.Item>
                      <AForm.Item label="样式" name={['attrs', 'line', 'strokeDasharray']}>
                        <ASelect>
                          <Option value="solid">实线</Option>
                          <Option value="5 5">虚线</Option>
                          <Option value="1 5">点线</Option>
                        </ASelect>
                      </AForm.Item>
                      <AForm.Item label="层级" name="zIndex">
                        <AInputNumber
                          style={{ width: '100%' }}
                          min={zIndexRange.min}
                          max={zIndexRange.max}
                        />
                      </AForm.Item>
                    </>
                  ),
                },
              ]}
            />
          </div>
        ),
      },
      {
        key: '2',
        label: '箭头',
        children: (
          <div className="p-4 pt-0">
            <ACollapse
              defaultActiveKey={['target', 'source']}
              ghost
              items={[
                {
                  key: 'target',
                  label: '目标箭头',
                  children: (
                    <>
                      <AForm.Item label="类型" name={['attrs', 'line', 'targetMarker', 'name']}>
                        <ASelect>
                          <Option value="classic">经典</Option>
                          <Option value="block">块</Option>
                          <Option value="diamond">菱形</Option>
                          <Option value="circle">圆形</Option>
                          <Option value="circlePlus">圆形+</Option>
                          <Option value="ellipse">椭圆</Option>
                          <Option value="cross">十字</Option>
                          <Option value="async">异步</Option>
                          <Option value="">无</Option>
                        </ASelect>
                      </AForm.Item>
                      <AForm.Item label="大小" name={['attrs', 'line', 'targetMarker', 'size']}>
                        <AInputNumber style={{ width: '100%' }} min={1} />
                      </AForm.Item>
                      <AForm.Item label="填充色" name={['attrs', 'line', 'targetMarker', 'fill']}>
                        <AColorPicker showText presets={colorPresets} />
                      </AForm.Item>
                    </>
                  ),
                },
                {
                  key: 'source',
                  label: '源头箭头',
                  children: (
                    <>
                      <AForm.Item label="类型" name={['attrs', 'line', 'sourceMarker', 'name']}>
                        <ASelect>
                          <Option value="classic">经典</Option>
                          <Option value="block">块</Option>
                          <Option value="diamond">菱形</Option>
                          <Option value="circle">圆形</Option>
                          <Option value="circlePlus">圆形+</Option>
                          <Option value="ellipse">椭圆</Option>
                          <Option value="cross">十字</Option>
                          <Option value="async">异步</Option>
                          <Option value="">无</Option>
                        </ASelect>
                      </AForm.Item>
                      <AForm.Item label="大小" name={['attrs', 'line', 'sourceMarker', 'size']}>
                        <AInputNumber style={{ width: '100%' }} min={1} />
                      </AForm.Item>
                      <AForm.Item label="填充色" name={['attrs', 'line', 'sourceMarker', 'fill']}>
                        <AColorPicker showText presets={colorPresets} />
                      </AForm.Item>
                    </>
                  ),
                },
              ]}
            />
          </div>
        ),
      },
      {
        key: '3',
        label: '路径',
        children: (
          <div className="p-4 pt-0">
            <ACollapse
              defaultActiveKey={['routing']}
              ghost
              items={[
                {
                  key: 'routing',
                  label: '路径风格',
                  children: (
                    <>
                      <AForm.Item label="折线风格" name={['router', 'name']}>
                        <ASelect>
                          <Option value="normal">直线</Option>
                          <Option value="orth">正交折线</Option>
                          <Option value="oneSide">受限正交</Option>
                          <Option value="manhattan">曼哈顿</Option>
                          <Option value="metro">地铁线</Option>
                          <Option value="er">ER图</Option>
                        </ASelect>
                      </AForm.Item>
                      <AForm.Item label="连接处风格" name={['connector', 'name']}>
                        <ASelect>
                          <Option value="normal">直角</Option>
                          <Option value="rounded">圆角</Option>
                          <Option value="smooth">平滑</Option>
                        </ASelect>
                      </AForm.Item>
                    </>
                  ),
                },
              ]}
            />
          </div>
        ),
      },
    ];

    return <ATabs defaultActiveKey="1" size="small" centered items={edgeTabs} />;
  };

  return (
    <div className="h-full flex flex-col property-panel-compact">
      <div className="p-4 border-b border-gray-200">
        <ASpace>
          {isNode && (
            <AButton
              icon={<CopyOutlined />}
              onClick={() => onDuplicateElement(selectedElement!.id)}
              size="small"
            >
              复制
            </AButton>
          )}
          {selectedElement && (
            <AButton
              icon={<DeleteOutlined />}
              danger
              onClick={() => onRemoveElement(selectedElement!.id)}
              size="small"
            >
              删除
            </AButton>
          )}
        </ASpace>
      </div>

      <div className="flex-1 overflow-y-auto">
        {!selectedElement ? (
          <div className="property-panel-compact">
            <AForm form={canvasForm} layout="vertical" onValuesChange={handleCanvasValuesChange}>
              <ATabs defaultActiveKey="background" centered>
                <ATabs.TabPane tab="背景设置" key="background">
                  <div className="p-4 pt-0">
                    <AForm.Item label="启用背景" name="backgroundVisible" valuePropName="checked">
                      <ASwitch size="small" />
                    </AForm.Item>
                    <AForm.Item label="背景颜色" name="backgroundColor">
                      <AColorPicker showText presets={colorPresets} />
                    </AForm.Item>
                    <AForm.Item
                      label="显示图片"
                      name="backgroundImageEnabled"
                      valuePropName="checked"
                    >
                      <ASwitch size="small" />
                    </AForm.Item>
                    {backgroundImageEnabled && (
                      <>
                        <AForm.Item label="背景图片" name="backgroundImageUrlFileList">
                          <CustomUpload
                            maxCount={1}
                            multiple={false}
                            accept="image/png, image/jpeg, image/gif, image/svg+xml"
                            listType="picture-card"
                          />
                        </AForm.Item>
                        <AForm.Item label="图片适应" name="backgroundImageFit">
                          <ASelect>
                            <Option value="cover">覆盖 (Cover)</Option>
                            <Option value="contain">适应 (Contain)</Option>
                            <Option value="fill">拉伸 (Fill)</Option>
                          </ASelect>
                        </AForm.Item>
                        <AForm.Item label="图片重复" name="backgroundImageRepeat">
                          <ASelect>
                            <Option value="repeat">平铺 (Repeat)</Option>
                            <Option value="no-repeat">不重复 (No Repeat)</Option>
                            <Option value="repeat-x">水平重复 (Repeat-X)</Option>
                            <Option value="repeat-y">垂直重复 (Repeat-Y)</Option>
                          </ASelect>
                        </AForm.Item>
                        <AForm.Item label="图片位置" name="backgroundImagePosition">
                          <ASelect>
                            <Option value="center">居中</Option>
                            <Option value="left top">左上</Option>
                            <Option value="left center">左中</Option>
                            <Option value="left bottom">左下</Option>
                            <Option value="right top">右上</Option>
                            <Option value="right center">右中</Option>
                            <Option value="right bottom">右下</Option>
                            <Option value="center top">中上</Option>
                            <Option value="center bottom">中下</Option>
                          </ASelect>
                        </AForm.Item>
                        <AForm.Item label="透明度" name="backgroundOpacity">
                          <ASlider min={0.05} max={1} step={0.05} />
                        </AForm.Item>
                      </>
                    )}
                  </div>
                </ATabs.TabPane>
                <ATabs.TabPane tab="网格设置" key="grid">
                  <div className="p-4 pt-0">
                    <AForm.Item label="启用网格" name="gridVisible" valuePropName="checked">
                      <ASwitch size="small" />
                    </AForm.Item>
                    <AForm.Item label="网格类型" name="gridType">
                      <ASelect>
                        <Option value="dot">点状</Option>
                        <Option value="fixedDot">固定点状</Option>
                        <Option value="mesh">网格</Option>
                        <Option value="doubleMesh">双层网格</Option>
                      </ASelect>
                    </AForm.Item>
                    <AForm.Item label="网格大小" name="gridSize">
                      <ASlider min={1} max={50} step={1} />
                    </AForm.Item>
                    <AForm.Item label="网格颜色" name="gridColor">
                      <AColorPicker showText presets={colorPresets} />
                    </AForm.Item>
                    <AForm.Item label="网格粗细" name="gridThickness">
                      <ASlider min={0.5} max={10} step={0.5} />
                    </AForm.Item>
                    {gridType === 'doubleMesh' && (
                      <>
                        <AForm.Item label="次网格颜色" name="gridColorSecond">
                          <AColorPicker showText presets={colorPresets} />
                        </AForm.Item>
                        <AForm.Item label="次网格粗细" name="gridThicknessSecond">
                          <ASlider min={0.5} max={10} step={0.5} />
                        </AForm.Item>
                        <AForm.Item label="缩放系数" name="gridFactor">
                          <ASlider min={1} max={10} step={1} />
                        </AForm.Item>
                      </>
                    )}
                  </div>
                </ATabs.TabPane>
              </ATabs>
            </AForm>
          </div>
        ) : (
          <AForm form={form} layout="vertical" onValuesChange={handleValuesChange}>
            {isNode && renderNodeProperties()}
            {isEdge && renderEdgeProperties()}
          </AForm>
        )}
      </div>
    </div>
  );
};

export default PropertyPanel;
